{% extends 'layout.html' %}
{% block content %}
{% load static %}
<link href="{% static 'css/user-view.css' %}" rel="stylesheet">

<div class="py-5 text-center">
  <h2>更改密码</h2>
</div>

<div class="row g-5 justify-content-center">
  <div class="col-md-8 col-lg-6">
    <form id="changePasswordForm">
      <!-- 原密码输入框 -->
      <div class="mb-3">
        <label for="init_password" class="form-label">原密码</label>
        <input type="password" class="form-control" id="init_password" name="init_password" required>
      </div>

      <!-- 新密码输入框 -->
      <div class="mb-3">
        <label for="current_password" class="form-label">新密码</label>
        <input type="password" class="form-control" id="current_password" name="current_password" required>
      </div>

      <!-- 确认新密码输入框 -->
      <div class="mb-3">
        <label for="confirm_password" class="form-label">确认新密码</label>
        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
      </div>

      <!-- 提交按钮 -->
      <button type="button" class="w-100 btn btn-primary btn-lg" id="changePasswordButton">提交</button>
    </form>
  </div>
</div>

<script>
  document.getElementById('changePasswordButton').addEventListener('click', async function(event) {
    event.preventDefault();

    const csrfToken = '{{ csrf_token }}';
    const formData = new FormData(document.getElementById("changePasswordForm"));

    fetch("/myapp/change_password/", {
      method: 'POST',
      headers: {
        'X-CSRFToken': csrfToken
      },
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      alert(data.message);  // 显示成功或错误消息
    })
    .catch(error => {
      alert("请求失败，请稍后重试！");
      console.error('Error:', error);
    });
  });
</script>

{% endblock %}
